<?php
/**
 * [商网通 System] Copyright swtshop.cn
 * QQ: 1170787711
 * Author: gj.name
 * This is NOT a freeware
*/
defined('IN_UQ') or exit('Access Denied');
class plug_uqcms extends control
{
    function __construct()
    {
        $this->aid = $_SESSION['admin']['aid'];
        $this->api_link = cfg('yun_url');
        parent::__construct();
    }
    function index()
    {
        $all = $this->db->get_all("select * from " . table('plug') . " order by id desc");
        if ($all) {
            foreach ($all as $v) {
                $list[] = $v;
            }
            $data['list'] = $list;
            $this->assign('data', $data);
        }
        if (!extension_loaded('zip')) {
            $this->assign('load_zip', '1');
        }
        $this->display();
    }
    function version_new()
    {
        $vname = isset($_GET['vname']) ? trim($_GET['vname']) : error_json('版本名称错误');
        $get_url = $this->api_link . 'plug/api_upgrade?vname=' . $vname;
        $result_json = curl::get($get_url);
        echo $result_json;
    }
    function yun()
    {
        $site_url = cfg('site_url');
        $admin_file = basename($_SERVER['PHP_SELF']);
        $site_url = base64_encode($site_url . $admin_file);
        header('Location:' . $this->api_link . 'plug/index?addr=' . $site_url);
    }
    function version()
    {
        $name = isset($_GET['name']) ? trim($_GET['name']) : showmsg('版本名称错误');
        $row = $this->db->get_one("select * from " . table('plug') . " where name = '" . $name . "'");
        if ($row['id']) {
            $this->assign('row', $row);
        }
        $this->display();
    }
    function install()
    {
        set_time_limit(0);
        $vname = !empty($_GET['vname']) ? $_GET['vname'] : exit('版本错误');
        $row = $this->db->get_one("select * from " . table('plug') . " where name = '" . $vname . "'");
        if (!$row['id']) {
            $this->del_upgrade_dir();
            $result = curl::get($this->api_link . 'plug/api_install?vname=' . $vname . '&web=' . cfg('yunapi_web') . "&secret=" . cfg('yunapi_secret'));
            $result = json_decode($result);
            if (@$result->error == '0') {
                $zip_name = $result->version . ".zip";
                $save_path = UQCMS_PATH . 'temp/upgrade/download/';
                $newFile = $save_path . $zip_name;
                if ($result->download_url) {
                    if (!is_dir($save_path)) {
                        file::mk_dir($save_path);
                    }
                    curl::downloadFile($result->download_url, $newFile);
                    sleep(2);
                    $zip = new ZipArchive();
                    if ($zip->open($newFile) !== TRUE) {
                        die("Could not open archive");
                    }
                    $destination = UQCMS_PATH . 'temp/upgrade/cover';
                    $zip->extractTo($destination);
                    $zip->close();
                    $this->cover_file_func();
                    $setarr['name'] = $vname;
                    $setarr['title'] = $result->title;
                    $setarr['desc'] = $result->desc;
                    $setarr['version'] = $result->version;
                    $setarr['addtime'] = time();
                    $query = $this->db->add(table('plug'), $setarr);
                    if ($query) {
                        showmsg('添加成功', '?m=plug&a=index');
                    } else {
                        exit('添加失败');
                    }
                } else {
                    exit('获取失败，URL');
                }
            } else {
                exit('获取失败：' . @$result->msg);
            }
        } else {
            exit('已经安装');
        }
    }
    public function js_load($str)
    {
        echo "<script type=\"text/javascript\">updateProgress('" . $str . "');</script>";
        ob_flush();
        flush();
    }
    function version_update()
    {
        $this->display('plug/upgrade');
    }
    function version_download()
    {
        $vname = !empty($_GET['vname']) ? $_GET['vname'] : exit('版本名称不能为空');
        $vid = $_GET['vid'];
        set_time_limit(0);
        $this->del_upgrade_dir();
        $this->display('plug/upgrade');
        ob_flush();
        flush();
        $this->version_download_func($vname, $vid);
        echo "<script type=\"text/javascript\">add_url('?m=plug&a=version_decode_zip&vname=" . $vname . "&vid=" . $vid . "', '还原文件');</script>";
    }
    public function version_download_func($vname, $version_id)
    {
        $get_url = $this->api_link . 'plug/api_upgrade?vname=' . $vname . '&vid=' . $version_id;
        $result_json = curl::get($get_url);
        $result = json_decode($result_json);
        if ($result->error == '0') {
            $zip_name = $result->version_id . ".zip";
            $save_path = UQCMS_PATH . 'temp/upgrade/download/';
            $newFile = $save_path . $zip_name;
            if ($result->download_url != '') {
                if (!is_dir($save_path)) {
                    file::mk_dir($save_path);
                }
                @unlink($newFile);
                $download_result = curl::downloadFile($result->download_url, $newFile);
                if ($download_result['filesize'] > 0) {
                    $this->js_load('下载升级版本成功: ' . $result->version_id);
                } else {
                    $this->js_load('下载失败，内容为空: ' . $result->version_id);
                }
                sleep(1);
                $this->version_download_func($vname, $result->next_version_id);
            } else {
                $this->js_load('无法获取下载地址');
            }
        } else {
            $this->js_load('已经下载完毕，其他信息：' . $result->msg);
        }
    }
    function version_decode_zip()
    {
        $vname = $_GET['vname'];
        $version_id = $_GET['vid'];
        set_time_limit(0);
        $this->display('plug/upgrade');
        ob_flush();
        flush();
        $result = file::get_file_list('temp/upgrade/download');
        if ($result) {
            $zip = new ZipArchive();
            foreach ($result as $v) {
                $yuanwenjian = UQCMS_PATH . $v;
                if ($zip->open($yuanwenjian) !== TRUE) {
                    die("Could not open archive");
                }
                $destination = UQCMS_PATH . 'temp/upgrade/cover';
                $zip->extractTo($destination);
                $this->js_load('解压:' . $v . '成功');
            }
            $zip->close();
        }
        ob_flush();
        flush();
        sleep(1);
        echo "<script>location.href=\"?m=plug&a=version_decode_list&vname=" . $vname . "&vid=" . $version_id . "\";</script>";
    }
    function version_decode_list()
    {
        $vname = $_GET['vname'];
        $version_id = $_GET['vid'];
        $result = file::get_file_list(UQCMS_PATH . 'temp/upgrade/cover', 'upgrade/cover');
        if ($result) {
            foreach ($result as $v) {
                $f['name'] = $v;
                $size = filesize(UQCMS_PATH . 'temp/upgrade/cover' . $v);
                if ($size == '0') {
                    $f['size'] = '/';
                } else {
                    $f['size'] = format_bytes($size);
                }
                $file[] = $f;
            }
        }
        $this->assign('file', $file);
        $this->display('plug/upgrade');
    }
    function cover_do()
    {
        $vname = !empty($_GET['vname']) ? trim($_GET['vname']) : exit('位置覆盖类型错误');
        if (cfg('site_local')) {
            $this->assign('msg', '本地测试环境，禁止更新，只对版本号更新。');
        } else {
            $this->cover_file_func();
        }
        $result_json = curl::get($this->api_link . 'plug/api_upgrade?vname=' . $vname);
        $result = json_decode($result_json);
        if ($result->error == '0') {
            $version_id = $result->version_id;
            $query = $this->db->update(table('plug'), array('version' => $version_id), " name = '" . $vname . "'");
        }
        $this->display('plug/upgrade');
    }
    function cover_file_func()
    {
        $sql_file = UQCMS_PATH . 'temp/upgrade/cover/data/sql/sql_update.sql';
        $file = file::read_file($sql_file);
        if ($file) {
            $sql_arr = explode(';', $file);
            $loop = 0;
            $count = 0;
            $this->db->autocommit();
            foreach ($sql_arr as $k => $v) {
                if (trim($v) != '') {
                    $this->db->query($v);
                    $query = true;
                    if ($query) {
                        $count++;
                    }
                    $loop++;
                }
            }
            if ($count == $loop && $count > '0') {
                $this->db->commit();
                $this->cover_file();
                $this->assign('msg', '更新成功');
            } else {
                $this->db->rollback();
            }
        } else {
            $this->cover_file();
        }
    }
    function cover_file()
    {
        $query = file::copy_dir(UQCMS_PATH . 'temp/upgrade/cover', UQCMS_PATH . '/');
        if ($query) {
            $this->del_upgrade_dir();
        } else {
            echo '无文件复制<br>';
        }
    }
    function del_upgrade_dir()
    {
        file::del_dir(UQCMS_PATH . 'temp/upgrade/download');
        file::del_dir(UQCMS_PATH . 'temp/upgrade/cover');
    }
}